package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.ams.domain.AmsAssetRepairRecord;
import com.ruoyi.ams.domain.AmsAssetRepairRecordDetail;
import com.ruoyi.ams.service.AmsReusingService;
import com.ruoyi.ams.service.IAmsAssetRepairRecordDetailService;
import com.ruoyi.ams.service.IAmsAssetRepairRecordService;
import com.ruoyi.common.core.domain.KeyValueVo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 维修信息登记Controller
 * 
 * @author yfkj
 * @date 2022-05-16
 */
@RestController
@RequestMapping("/ams/record")
public class AmsAssetRepairRecordController extends BaseController
{
    @Autowired
    private IAmsAssetRepairRecordService amsAssetRepairRecordService;

    @Autowired
    private AmsReusingService amsReusingService;
    @Autowired
    private IAmsAssetRepairRecordDetailService assetRepairRecordDetailService;
//    @Autowired
//    private RemoteUserService remoteUserService;
    @Autowired
    private SysUserController userController;

    /**
     * 查询维修信息登记列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:list")
    @ApiOperation(value = "获取维修信息登记列表", response = AmsAssetRepairRecord.class)
    @GetMapping("/getAmsAssetRepairRecordList")
    public TableDataInfo getAmsAssetRepairRecordList(AmsAssetRepairRecord amsAssetRepairRecord)
    {
        QueryWrapper<AmsAssetRepairRecord> wrapper = new QueryWrapper<>();
        if (amsAssetRepairRecord.getStatus() != null) {
            wrapper.eq(AmsAssetRepairRecord.STATUS, amsAssetRepairRecord.getStatus());
        }
        wrapper.orderByDesc(AmsAssetRepairRecord.REPAIR_RECORD_ID);
        startPage();
        List<AmsAssetRepairRecord> list = amsAssetRepairRecordService.list(wrapper);

        R<Map<Long, SysUser>> allUsers = userController.getAllUsers();
        if (allUsers.getCode() == R.FAIL) {
            return amsReusingService.resovleError();
        }
        Map<Long, SysUser> userMap = allUsers.getData();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy.MM.dd");

        List<AmsAssetRepairRecordDetail> recordDetails = assetRepairRecordDetailService.list();

        HashMap<Long, String> assetIdTypeNameMap = amsReusingService.getAssetIdTypeNameMap();

        for (AmsAssetRepairRecord record : list) {
            if (record.getChargerId() != null) {
                SysUser sysUser = userMap.get(record.getChargerId());
                if (sysUser != null) {
                    record.setChargerName(sysUser.getNickName());
                }
            }
            if (record.getFaultReportId() != null) {
                SysUser sysUser = userMap.get(record.getFaultReportId());
                if (sysUser != null) {
                    record.setFaultReportName(sysUser.getNickName());
                }
            }
            if (record.getBusinessTime() != null) {
                record.setBusinessTimeStr(fmt.format(new Date(record.getBusinessTime())));
            }
            if (record.getRepairTime() != null) {
                record.setRepairTimeStr(fmt.format(new Date(record.getRepairTime())));
            }
            List<String> assetTypeNames = new ArrayList<>();
            for (AmsAssetRepairRecordDetail recordDetail : recordDetails) {
                if (recordDetail.getRepairRecordId().equals(record.getRepairRecordId())) {
                    String assetTypeName = assetIdTypeNameMap.get(recordDetail.getAssetId());
                    if (assetTypeName != null) {
                        assetTypeNames.add(assetTypeName);
                    }
                }
            }
            record.setAssetNames(assetTypeNames);
        }
        return getDataTable(list, 10);
    }

    /**
     * 获取维修信息登记详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:query")
    //@ApiOperation(value = "获取维修信息登记详情")
    @GetMapping(value = "/getAmsAssetRepairRecordById")
    public AjaxResult getAmsAssetRepairRecordById(@RequestParam("repairRecordId") Long repairRecordId)
    {
        return AjaxResult.success(amsAssetRepairRecordService.selectAmsAssetRepairRecordByRepairRecordId(repairRecordId));
    }

    /**
     * 新增维修信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:add")
    @Log(title = "维修信息登记", businessType = BusinessType.INSERT)
    @ApiOperation(value = "新增维修信息登记")
    @PostMapping(value = "/addAmsAssetRepairRecord")
    public AjaxResult addAmsAssetRepairRecord(@RequestBody AmsAssetRepairRecord amsAssetRepairRecord)
    {
        //新增维修信息
        amsAssetRepairRecord.setSn(amsReusingService.createSn());
        amsAssetRepairRecordService.save(amsAssetRepairRecord);
        //新增维修信息明细
        if (amsAssetRepairRecord.getRepairRecords().size() == 0) {
            return AjaxResult.error("请至少选择一个资产");
        }
        List<AmsAssetRepairRecordDetail> recordDetails = new ArrayList<>();
        for (AmsAssetRepairRecordDetail repairRecord : amsAssetRepairRecord.getRepairRecords()) {
            AmsAssetRepairRecordDetail recordDetail = new AmsAssetRepairRecordDetail();
            BeanUtils.copyProperties(repairRecord, recordDetail);
            recordDetail.setRepairRecordId(amsAssetRepairRecord.getRepairRecordId());
            recordDetails.add(recordDetail);
        }
        assetRepairRecordDetailService.saveBatch(recordDetails);
        return AjaxResult.success();
    }

    /**
     * 修改维修信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:edit")
    @Log(title = "维修信息登记", businessType = BusinessType.UPDATE)
    //@ApiOperation(value = "修改维修信息登记")
    @PostMapping(value = "/editAmsAssetRepairRecord")
    public AjaxResult editAmsAssetRepairRecord(@RequestBody AmsAssetRepairRecord amsAssetRepairRecord)
    {
        //修改维修信息
        amsAssetRepairRecordService.updateById(amsAssetRepairRecord);
        //修改维修信息明细
        if (amsAssetRepairRecord.getRepairRecords().size() > 0) {
            //先删除原来的维修信息明细
            assetRepairRecordDetailService.remove(new QueryWrapper<AmsAssetRepairRecordDetail>()
                    .eq(AmsAssetRepairRecordDetail.REPAIR_RECORD_ID, amsAssetRepairRecord.getRepairRecordId()));
            //然后保存现有的维修信息明细
            List<AmsAssetRepairRecordDetail> recordDetails = new ArrayList<>();
            for (AmsAssetRepairRecordDetail repairRecord : amsAssetRepairRecord.getRepairRecords()) {
                AmsAssetRepairRecordDetail recordDetail = new AmsAssetRepairRecordDetail();
                BeanUtils.copyProperties(repairRecord, recordDetail);
                recordDetail.setRepairRecordId(amsAssetRepairRecord.getRepairRecordId());
                recordDetails.add(recordDetail);
            }
            assetRepairRecordDetailService.saveBatch(recordDetails);
        }
        return AjaxResult.success();
    }

    /**
     * 删除维修信息登记
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:remove")
    @Log(title = "维修信息登记", businessType = BusinessType.DELETE)
	@GetMapping("/removeAmsAssetRepairRecords")
    public AjaxResult removeAmsAssetRepairRecords(@RequestParam Long[] repairRecordIds)
    {
        return toAjax(amsAssetRepairRecordService.deleteAmsAssetRepairRecordByRepairRecordIds(repairRecordIds));
    }

    @GetMapping("/getAmsAssetRepairRecordNamesForSelect")
    //@ApiOperation(value = "获取维修信息登记名称列表用于下拉搜索")
    public AjaxResult getAmsAssetRepairRecordNamesForSelect()
    {
        List<AmsAssetRepairRecord> list = amsAssetRepairRecordService.list();//自行加条件
        List<KeyValueVo> resultList = new ArrayList<>();
        for (AmsAssetRepairRecord amsAssetRepairRecord: list ) {
            KeyValueVo vo = new KeyValueVo();
            //vo.setKey(it.getId());
            //vo.setValue(it.getName());
            resultList.add(vo);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 导出维修信息登记列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:record:export")
    @Log(title = "维修信息登记", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAmsAssetRepairRecord")
    public String exportAmsAssetRepairRecord(HttpServletResponse response, AmsAssetRepairRecord amsAssetRepairRecord) throws IOException
    {
        List<AmsAssetRepairRecord> list = amsAssetRepairRecordService.selectAmsAssetRepairRecordList(amsAssetRepairRecord);
        ExcelUtil<AmsAssetRepairRecord> util = new ExcelUtil<AmsAssetRepairRecord>(AmsAssetRepairRecord.class);
        util.exportExcel(response, list, "维修信息登记数据");
        return "";
    }

}
